var app = getApp();
var time = require('../../../utils/util.js');
Page({
  data: {
    getBooksByCondition: app.globalData.bookUrl + '/book/getBooks.do',
    borrow: app.globalData.bookUrl + '/user/useBook.do',
    register: app.globalData.bookUrl + '/user/userRegister.do', //注册
    userInfo: app.globalData.bookUrl + '/user/userInfo.do', //判断是否已注册
    getBookType: app.globalData.bookUrl + '/book/bookType.do',
    notReturned: app.globalData.bookUrl + '/user/getBorrowing.do', //获取当前用户未归还图书id
    backBook: app.globalData.bookUrl + '/user/backBook.do',
    getEvaluateURL: app.globalData.bookUrl + '/evaluate/selectEvaluate.do',//查询评价
    subPraiseURL: app.globalData.bookUrl + '/evaluate/praise.do',//上传点赞
    getBorrowingsURL: app.globalData.bookUrl + '/Borrowing/getBorrowings.do',//借阅记录
    praiseURL: app.globalData.bookUrl + '/evaluate/praise.do',//点赞记录
    hiddenmodalput: true,
    praiseNum:0,
    sumBorrowingsList: [],
    readerNameing: "",
    evaluateList:[],
    bookidL: '',
    scanflag: 0,
    color:'',
    // num: 4,//后端给的分数，显示的星星
    illume: '',//点亮的星星数
    illume_no: '',//没有点亮的星星数
    _num: 0,
  },
  modalinput: function () {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  getReadersName: function (e) {
    var that = this;
    that.setData({
      readerNameing: e.detail.value
    });
  },
  //取消按钮  
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },

  //确认  
  confirm: function () {
    var that = this;
    if (that.data.readerNameing == "") {
      wx.showToast({
        title: '请填写姓名',
        image: '../../images/icon/fail.png',
        duration: 2000
      })
      that.setData({
        hiddenmodalput: !that.data.hiddenmodalput
      })
    } else {
      that.setData({
        readerName: that.data.readerNameing
      });
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000
      })
      that.setData({
        hiddenmodalput: true
      })
      that.userRegister(that.data.register, that.data.openId, that.data.nickName, that.data.avatarUrl, that.data.readerName);
    }
  },
  onShow:function(e){
    var that = this;
    that.getBooksById();
  },
  // wx.startPullDownRefresh
  onLoad: function (options) {
  
    var that = this;
    var isBackEstimate = options.isBackEstimate;
    that.setData({
      isBackEstimate: isBackEstimate
    });
    wx.getStorage({
      key: 'openid',
      success(res) {
        that.setData({
          openId: res.data
        });
      }
    })
    if (isBackEstimate!='yes'){//判断是否是评价返回的此页面
      var scanflag = options.scanflag;
      var bookid = options.bookId;
      var book = options.book;
      if (options.bookType == undefined) {
        var bookType = book.split('-')[0]
      } else {
        var bookType = options.bookType;
      }
      if (bookid == undefined) {
        bookid = "";
      }
      var bookNumber = options.bookNumber;
      if (bookNumber == undefined) {
        bookNumber = "";
      }
      var bookTypeId = options.bookTypeId;
      if (bookTypeId == undefined) {
        bookTypeId = "";
      }
     
      that.setData({
        scanflag: scanflag,
        bookidL: bookid,
        bookNumber: bookNumber,
        bookTypeId: bookTypeId,
        bookType: bookType
      });
      wx.setStorageSync('scanflag', scanflag);
      wx.setStorageSync('bookidL', bookid);
      wx.setStorageSync('bookNumber', bookNumber);
      wx.setStorageSync('bookTypeId', bookTypeId);
      wx.setStorageSync('bookType', bookType);
    }
    that.setData({
      scanflag: wx.getStorageSync('scanflag')
    });
    that.getBooksById();
    // var collected = wx.getStorageSync('collected');
    // if (collected) {
    //   that.setData({
    //     collected: collected
    //   });
    // }else{
    //   that.setData({
    //     collected: 0
    //   });
    //   wx.setStorageSync('collected', 0)
    // }
  },
  onUnload: function (e) {
    var that = this;
    console.log("借书页返回")
    // var estimateBack = that.data.isBackEstimate
    // if (estimateBack == 'yes'){
    //   wx.switchTab({
    //     url: '../../library/library'
    //   })
    // }else{
      wx.switchTab({
        url: '../library/library'
      })
    // }
  },
  onGotUserInfo: function (e) {
    var that = this;
    var nickName = e.detail.userInfo.nickName;
    var avatarUrl = e.detail.userInfo.avatarUrl;
    that.setData({
      nickName: nickName,
      avatarUrl: avatarUrl
    });
    that.getReaderName(that.data.userInfo, that.data.openId);
  },
  getReaderName: function (userInfoURL, openId) {
    var that = this;
    wx.request({
      url: userInfoURL,
      data: {
        openId: openId
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        if (res.data.data.content[0].readersName == null || res.data.data.content[0].readersName == "") {
          that.setData({
            hiddenmodalput: !that.data.hiddenmodalput
          })
        } else {
          that.setData({
            readerName: res.data.data.content[0].readersName
          });
          that.userRegister(that.data.register, that.data.openId, that.data.nickName, that.data.avatarUrl, res.data.data.content[0].readersName);
        }
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  clickbackBook: function () {
    var that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        that.setData({
          openId: res.data
        });
        that.backBook(that.data.openId);
      }
    })

  },
  backBook: function (openId) {
    var that = this;
    var backBook = that.data.backBook;
    var bookId = that.data.bookId;

    wx.request({
      url: backBook,
      data: {
        bookId: bookId,
        openId: openId
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '归还成功',
            duration: 1000,
            icon: 'success'
          })
          that.setData({
            bookState: 1
          });
        } else if (res.data.code == -3003) {
          wx.showToast({
            title: '不能归还',
            duration: 1000,
            image: '../../../images/icon/fail.png',
          })
        }
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  userRegister: function (registerURL, openId, nickName, avatarUrl, readerName) {
    var that = this;
    wx.showLoading({
      title: '借书中...'
    })
    wx.request({
      url: registerURL,
      data: {
        openId: openId,
        headImg: avatarUrl,
        nickName: nickName,
        readersName: readerName
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        that.borrowBook(that.data.borrow, that.data.bookId, that.data.openId, that.data.readerName);
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  getBooksById: function () {
    var that = this;
    var getBooksByCondition = that.data.getBooksByCondition; //获取图书URL
    // var bookId = that.data.bookidL; //获取图书URL
    // var bookNumber = that.data.bookNumber;
    // var bookTypeId = that.data.bookTypeId;
    var bookId = wx.getStorageSync('bookidL'); //获取图书URL
    var bookNumber = wx.getStorageSync('bookNumber');
    var bookTypeId = wx.getStorageSync('bookTypeId');
    wx.request({
      url: getBooksByCondition,
      data: {
        bookId: bookId,
        bookNumber: bookNumber,
        bookTypeId: bookTypeId
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        that.showAllBooksByBookId(res.data.data); //向前台传递数据
        that.getTwoEvaluate();
        that.getThreeBorrowings();
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  getTwoEvaluate:function(){
    var that = this;
    wx.request({
      url: that.data.getEvaluateURL,
      data: {
        bookName: that.data.bookName,
        openid:that.data.openId,
        praise:"1",
        size:2,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        that.showTwoEvaluate(res.data.data); //向前台传递数据
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  getFeeling:function(e){
    var that = this;
    if (e.target.id){
      that.setData({
        color: "#19b5ee"
      })
    }
   
    wx.showLoading({
      title: '玩命打开中',
    })
    wx.downloadFile({
      url: app.globalData.bookUrl + encodeURIComponent(e.target.id).replace(/\%2F/g,"/"),
      success(res) {
        wx.hideLoading();
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath,
          success(res) {
            console.log('打开文档成功')
          },
          fail: function (error) {
            // fail
            wx.showToast({
              title: '打开失败',
              duration: 1000,
              image: '../../../images/icon/fail.png',
            })
          }
        })
      }
    })
  },
  getThreeBorrowings: function () {
    var that = this;
    wx.request({
      url: that.data.getBorrowingsURL,
      data: {
        bookName: that.data.bookName,
        size: 3,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res.data.data)
        that.showThreeBorrowingsBooks(res.data.data); //向前台传递数据
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  },
  showThreeBorrowingsBooks: function (sumBorrowing) {
    var that = this;
    var sumBorrowings = [];
    if (sumBorrowing != null) {
      for (var idx in sumBorrowing.content) {
        var content = sumBorrowing.content[idx];
        var readersName = content.readersName;
        var headImg = content.headImg;
        var borrowingTime = time.formatTime(content.borrowingTime, 'Y-M-D h:m:s');
        var temp = {
          readersName: readersName,
          headImg: headImg,
          borrowingTime: borrowingTime
        }
        sumBorrowings.push(temp);
      }
      that.setData({
        sumBorrowingsList: sumBorrowings
      });
    }
  },
  showTwoEvaluate: function (evaluate) {
    var that = this;
    var evaluates = [];
    if (evaluate != null) {
      for (var idx in evaluate.content) {
        var content = evaluate.content[idx];
        var bookScore = content.bookScore;
        var evaluateContent = content.evaluateContent;
        var readersName = content.readersName;
        var evaluateId = content.evaluateId;
        var headImg = content.headImg;
        var evaluateFeeling = content.evaluateFeeling;
        var praise = content.praise;
        var ispraise = content.ispraise;
        var openid = content.openId;
        var createTime = time.formatTime(content.createTime, 'Y-M-D h:m:s');
        var temp = {
          illume: bookScore,
          illume_no: 5 - bookScore,
          readersName: readersName,
          headImg : headImg,
          createTime: createTime,
          evaluateFeeling: evaluateFeeling,
          evaluateContent: evaluateContent,
          evaluateId: evaluateId,
          praise: praise,
          ispraise: ispraise,
          openid: openid,
        }
        evaluates.push(temp);
      }
      that.setData({
        evaluateList: evaluates
      });
    }
  },
  showAllBooksByBookId: function (BooksById) {
    var that = this;
    var books = [];
    if (BooksById != null) {
      var content = BooksById.content[0];
      var bookImgSource = app.globalData.bookUrl + content.bookImg +'?' + Math.random() / 9999;
      var createTimeSource = time.formatTime(content.createTime, 'Y-M-D h:m:s');
      var bookTypeIdSource = content.bookTypeId;
      // var types = that.data.bookTypeList;
      var typeName = wx.getStorageSync('bookType');
      var temp = {
        bookId: content.bookId,
        authorSynopsis: content.authorSynopsis,
        bookImg: bookImgSource,
        bookName: content.bookName,
        createTime: createTimeSource,
        bookAuthor: content.bookAuthor,
        bookState: content.bookState,
        bookType: typeName,
        bookSynopsis: content.bookSynopsis,
      }
      books.push(temp);
      that.setData({
        booklistbyid: books,
        bookId: content.bookId,
        bookName: content.bookName,
        bookState: content.bookState
      });
    } else {
      wx.showToast({
        title: '暂无此书',
        duration: 3000,
        image: '../../../images/icon/fail.png',
      })
    }
  },
  borrowBook: function (borrowURL, bookId, openId, readersName) {
    var that = this;
    wx.request({
      url: borrowURL,
      data: {
        bookId: bookId,
        openId: openId,
        readersName: readersName
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 0) {
          wx.showToast({
            title: '借阅成功',
            duration: 1000,
            icon: 'success'
          })
          that.setData({
            bookState: 2
          });
        } else if (res.data.code == -2002) {
          wx.showToast({
            title: '该图书已借阅',
            duration: 1000,
            image: '../../../images/icon/fail.png',
          })
        } else if (res.data.code == -2003) {
          wx.showToast({
            title: '只允许借三本',
            duration: 1000,
            image: '../../../images/icon/fail.png',
          })
        }
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
    wx.navigateTo({
      url: "../../personal/personal"
    })
  },

  // selectPraise: function (evaluateId) {
  //   var that = this;
  //   var isParise = 0;
  //   return new Promise(function (resolve, reject) {
  //     wx.request({
  //       url: that.data.selectPraiseURL,
  //       data: {
  //         evaluateId: evaluateId,
  //         openid: that.data.openId,
  //       },
  //       method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
  //       header: {
  //         "Content-Type": "application/x-www-form-urlencoded"
  //       },
  //       success: (res) => {
  //         if (res.data.code != 0) {
  //           isParise = 0;
  //           resolve(isParise)
  //         } else {
  //           isParise = 1;
  //           resolve(isParise)
  //         }
  //         // that.setData({
  //         //   isParise: isParise
  //         // });
  //       },
  //       fail: (error)=> {
  //         // fail
  //         reject(error)
  //       }
  //     })
  //   })

  // },
  // 更改点赞状态
  onCollectionTap: function (event) {
    // 获取当前点击下标
    var that = this;
    var evaluateId = event.currentTarget.dataset.id;
    var collected = event.currentTarget.dataset.index;
    if (collected == 0) { //如果是没点赞+1
      collected =1;
    } else {
      collected = 0;
    }
    // that.selectPraise(evaluateId).then(function(isParise){
    //    collected=isParise
    // })
    wx.request({
      url: that.data.praiseURL,
      data: {
        evaluateId: evaluateId,
        openid: that.data.openId,
        praise: collected,
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        that.getTwoEvaluate(); //向前台传递数据
      },
      fail: function (error) {
        // fail
        console.log(error)
      }
    })
  
  },
  //评价——查看全部
  all: function () {
    var that = this;
    wx.navigateTo({
      url: "../check/check?bookName=" + that.data.bookName
    })
  },
  //借阅历史——查看更多
  history_all: function () {
    var that = this;
    wx.navigateTo({
      url: "../history/history?bookName=" + that.data.bookName
    })
  },
  //评价
  appraise: function () {
    var that = this;
    wx.navigateTo({
      url: "../estimate/estimate?bookId=" + that.data.bookId + "&bookName=" + that.data.bookName+ "&openId=" + that.data.openId +"&borrowFlag="+1
    })
  },
  //显示/隐藏  全部文章
  clickNum: function (e) {
    var thisnum = e.target.dataset.num
    if (thisnum == 1) {
      this.setData({
        _num: 0
      })
    } else {
      this.setData({
        _num: 1
      })
    }
  }, 

})